package zkclient;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.IZkStateListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.Watcher;


/**
 * Created by ZHANG on 2017/3/12.
 */
public class ClientListener {

    public static void main(String[] args)throws Exception{
        ZkClient zkClient = new ZkClient("localhost:2181",5000);
        zkClient.deleteRecursive("/zhang");
        zkClient.createPersistent("/zhang","1");
        //监听子节点的增、删事件
        zkClient.subscribeChildChanges("/zhang", (parentPath,currentChilds) -> System.out.println("subscribeChildChanges:"+parentPath+"/"+ currentChilds));

        //监听子节点的删除、更新
        zkClient.subscribeDataChanges("/zhang/wang", new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
                System.out.println(String.format("handleDataChange  s:%s\to:%s",s,o));
            }
            @Override
            public void handleDataDeleted(String s) throws Exception {
                System.out.println(String.format("删除s:%s",s));
            }
        });


        zkClient.subscribeStateChanges(new IZkStateListener() {
            @Override
            public void handleStateChanged(Watcher.Event.KeeperState keeperState) throws Exception {
                System.out.println(keeperState);
            }

            @Override
            public void handleNewSession() throws Exception {
                System.out.println("handleNewSession");
            }

            @Override
            public void handleSessionEstablishmentError(Throwable throwable) throws Exception {
                System.out.println(throwable);
            }
        });


        Thread.sleep(100000);
        zkClient.close();
    }

}
